import { ICalculator } from '../types';
import { calculateMonthlyInterestRate, calculateNumToStr, calculateWalkMonthly } from '../util';

const straightLineCalculator: ICalculator = (params) => {
  const { principal, interestRate, loanTerm } = params;

  let remainingPrincipal = principal;
  const monthlyInterestRate = calculateMonthlyInterestRate(interestRate);
  const monthlyPayment = (principal * monthlyInterestRate) / (1 - Math.pow(1 + monthlyInterestRate, -loanTerm));

  const calculateMonthly = () => {
    const interestPayment = remainingPrincipal * monthlyInterestRate;
    const monthlyPrincipal = monthlyPayment - interestPayment;
    remainingPrincipal -= monthlyPrincipal;

    return {
      monthlyPayment: calculateNumToStr(monthlyPayment),
      interestPayment: calculateNumToStr(interestPayment),
      monthlyPrincipal: calculateNumToStr(monthlyPrincipal),
      remainingPrincipal: calculateNumToStr(remainingPrincipal),
    };
  };

  return calculateWalkMonthly(params, calculateMonthly);
};

export default straightLineCalculator;
